package com.team.app.controller;


import java.util.Date;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.team.app.enums.ObjectType;
import com.team.app.enums.UrlFixed;
import com.team.app.model.Auth;
import com.team.app.model.AuthAcept;
import com.team.app.model.Company;
import com.team.app.model.Employee;
import com.team.app.model.Role;
import com.team.app.service.AuthAceptService;
import com.team.app.service.AuthService;
import com.team.app.service.CityService;
import com.team.app.service.EmployeeService;
import com.team.app.service.RoleService;
import com.team.app.util.BeanUtil;
import com.team.app.util.ConvertUtil;
import com.team.app.util.FormatUtil;


/**
 * Handles requests for the application home page.
 */
@Controller
public class EmployeeController extends AbstractController<Employee> {

	private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);	
	private final String PATH_BASE = "/employee";
	
	@Autowired	
	private EmployeeService employeeService;
	
	@Autowired	
	private RoleService roleService;
	
	@Autowired	
	private AuthService authService;
	
	@Autowired	
	private AuthAceptService authAceptService;
	
	@Autowired	
	private CityService cityService;
	
	private Employee emp ;
	
	//-----------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = PATH_BASE, method = {RequestMethod.GET, RequestMethod.POST})
	public String indexAction(Model model,HttpSession s,Employee obj) {	
		logger.info("EmployeeController index");   	
    	if(!checkView(s, PATH_BASE)){
    		return accessDenied();
    	}  
    	
		AuthAcept acept  = null;
		obj = obj != null ? obj : new Employee();
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		UrlFixed uri = UrlFixed.getByUrl(PATH_BASE);
		
		if(!loginAuth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){
			acept = authAceptService.find(Long.parseLong(uri.getKey()), loginAuth.getRoleId(), loginAuth);				
		}else{
			acept = new AuthAcept();
			acept.setActiveView(1L);
			acept.setActiveInsert(1L);
			acept.setActiveUpdate(1L);
			acept.setActiveDelete(1L);	
		}
		model.addAttribute("objs", employeeService.findAll(obj,loginAuth.getCompanyId()));
		s.setAttribute("acept", acept);
		model.addAttribute("obj", obj);	
		return PATH_BASE+"/index";
	}

	
	@Override
	@RequestMapping(value = PATH_BASE+"/add", method = {RequestMethod.GET, RequestMethod.POST})
	public String addAction(Model model,HttpSession s) {
		// TODO Auto-generated method stub
		if(!checkAdd(s, PATH_BASE)){
			return accessDenied();
    	}
		emp = new Employee();
		model.addAttribute("obj", emp);		
		model.addAttribute("cities", cityService.findAll());				
		return PATH_BASE+"/input";		
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/edit/{id}", method = {RequestMethod.GET, RequestMethod.POST})
	public String editAction(Model model,HttpSession s,@PathVariable("id")Long id) {
		// TODO Auto-generated method stub		
		if(!checkEdit(s, PATH_BASE)){
			return accessDenied();
    	} 
		emp = employeeService.find(id);
		model.addAttribute("obj", emp);		
		model.addAttribute("cities", cityService.findAll());		
		return PATH_BASE+"/input";
	}
	
	@Override
	@RequestMapping(value = PATH_BASE+"/back", method = {RequestMethod.GET, RequestMethod.POST})
	public String backAction(Model model,HttpSession s, Employee obj ) {
		// TODO Auto-generated method stub	
		
		model.addAttribute("obj", obj);		
		model.addAttribute("cities", cityService.findAll());		
		return PATH_BASE+"/input";
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/confirm", method = {RequestMethod.GET, RequestMethod.POST})
	public String confirmAction(Model model,HttpSession s,@ModelAttribute("obj") Employee obj ,BindingResult result) {
		// TODO Auto-generated method stub
		boolean excute = true;
		if(ConvertUtil.isEmplty(obj.getEmpMail())){
			setMessage(model,result,"empMail", "emp.email.blank");	
			excute = false;	
		}else{
			if(!FormatUtil.isEmail(obj.getEmpMail())){
				setMessage(model,result,"empMail", "role.name.blank");	
				excute = false;	
			}
		}
		if(ConvertUtil.isEmplty(obj.getEmpName())){
			setMessage(model,result,"empName", "emp.name.blank");	
			excute = false;	
		}
		if(ConvertUtil.isEmplty(obj.getEmpPhone())){
			setMessage(model,result,"empPhone", "emp.phone.blank");	
			excute = false;	
		}else{
			if(!FormatUtil.isPhone(obj.getEmpPhone())){
				setMessage(model,result,"empPhone", "emp.phone.invalid");	
				excute = false;	
			}
		}	
		if(ConvertUtil.isNull(obj.getEmpId()) || !ConvertUtil.isEqual(emp.getEmpMail(), obj.getEmpMail())){
			if(employeeService.existEmail(obj.getEmpMail())){
				setMessage(model,result,"empMail", "emp.email.exist");	
				excute = false;	
			}
		}
		
		
		if(!excute){
			model.addAttribute("obj", obj);	
			model.addAttribute("cities", cityService.findAll());
			return PATH_BASE+"/input";
		}		
		obj.setCityId(cityService.find(obj.getCityId().getCityId()));
		model.addAttribute("obj", obj );
		return PATH_BASE+"/confirm";
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/complete", method = {RequestMethod.GET, RequestMethod.POST})
	public String completeAction(Model model,HttpSession s,Employee obj ,BindingResult result) {
		// TODO Auto-generated method stub
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
				
		obj.setRoleId(new Role(99L));
		if(!ConvertUtil.isNull(emp)){			
			BeanUtil.copy(obj,emp);			
			employeeService.edit(emp);	
			model.addAttribute("obj", emp); 
		}else{	
			if(!loginAuth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){
				obj.setCompanyId(new Company(loginAuth.getCompanyId()));
			}			
			employeeService.create(obj);			
			Auth auth = new Auth();
			auth.setAccountName(obj.getEmpMail());
			auth.setPassword(ConvertUtil.md5Hash("abc@12345"));
			auth.setRoleId(obj.getRoleId().getRoleId());
			auth.setCompanyId(loginAuth.getCompanyId()); 
			auth.setObjectType(ObjectType.TYPE_EMPLOYEE.getKey());
			auth.setApproveBy(loginAuth.getAccountName());
			auth.setApproveDate(new Date());
			auth.setActive(1L);
			auth.setParentId(loginAuth.getId());
			authService.create(auth);
			model.addAttribute("obj", obj); 
		}
			
		return "redirect:"+PATH_BASE;
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/delete/{id}" ,method = {RequestMethod.GET, RequestMethod.POST})
	public String deleteAction(Model model,HttpSession s,@PathVariable("id")Long id) {	
		// TODO Auto-generated method stub
		if(!checkDelete(s, PATH_BASE)){
			return accessDenied();
    	} 
		Employee emp = employeeService.find(id);
		Auth authEmp = authService.find(emp.getEmpMail());
		if(authEmp != null){
			authService.remove(authEmp);
		}
		employeeService.remove(emp);
			
		return "redirect:"+PATH_BASE;
	}	
	
		
}
